﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using Tango.Core.Data;

namespace Tango.Data
{
    public class EFRepository<T> : IEFRepository<T> where T : class,new()
    {
        #region 变量
        protected readonly EFDaoContext _context;

        private IDbSet<T> _entities;
        #endregion

        #region 属性
        private IDbSet<T> Entities
        {
            get
            {
                if (_entities == null)
                    _entities = _context.Set<T>();
                return _entities;
            }

        }
        #endregion

        #region 构造
        public EFRepository(EFDaoContext context)
        {
            this._context = context;
        }

        #endregion

        #region 方法
        public IQueryable<T> GetAll()
        {
            return Entities;
        }

        public T Get(long ID)
        {
            return Entities.Find(ID);
        }

        public T Get(string ID)
        {
            return Entities.Find(ID);
        }

        public void Update(T entity)
        {
            _context.SaveChanges();
        }

        public void Add(T entity)
        {
            Entities.Add(entity);
            _context.SaveChanges();
        }

        public void Delete(T entity)
        {
            Entities.Remove(entity);
            _context.SaveChanges();
        }

        public void Delete(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {
            var query = Entities.Where(where);
            foreach (var item in query)
            {
                Entities.Remove(item);
            }
            _context.SaveChanges();
        }

        public T Get(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {
            return Entities.Where(where).FirstOrDefault();
        }

        public IQueryable<T> GetMany(System.Linq.Expressions.Expression<Func<T, bool>> where)
        {
            return Entities.Where(where);
        }
        #endregion
    }
}
